<?php

namespace backend\controllers;

use backend\models\AdminUser;
use backend\models\LoginForm;
use Yii;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

class LoginController extends \yii\web\Controller
{
    public $layout = 'login';

    public function behaviors ()
    {
        return [
            'access' => [
                'class' => AccessControl::className() ,
                'rules' => [
                    [
                        'actions' => [ 'login' ] , //允许未登录的用户访问登录操作
                        'allow'   => TRUE ,
                        'roles'   => [ '?' ] ,
                    ] ,
                    [
                        'actions' => [ 'logout' ] , //允许已登录的用户访问退出操作
                        'allow'   => TRUE ,
                        'roles'   => [ '@' ] ,
                    ] ,
                ] ,
            ] ,
            'verbs'  => [ //指定该规则用于匹配哪种请求方法（例如GET，POST）。 这里的匹配大小写不敏感。
                          'class'   => VerbFilter::className() ,
                          'actions' => [
                              'logout' => [ 'post' , 'get' ] ,
                          ] ,
            ] ,
        ];
    }

    public function actions ()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction' ,
            ] ,
        ];
    }

    /**
     * 登录
     */
    public function actionLogin ()
    {
        if ( !Yii::$app->user->isGuest ) {
            return $this->goHome();
        }
        $model = new LoginForm();

        $time = 3600 * 3; //登录之后3小时免登陆
        if ( $model->load( Yii::$app->request->post() ) && $model->login( $time ) ) {
            $user_info = AdminUser::findOne( Yii::$app->user->identity->getId() );
            $user_info->scenario = 'logout';
            $user_info->last_time = date('Y-m-d H:i:s',time());
            $user_info->last_ip = Yii::$app->request->userIP;
            $user_info->save( FALSE );
            $this->redirect( [ 'index/main' ] );
        } else {
            return $this->render( 'login' , [
                'model' => $model ,
            ] );
        }
    }

    /**
     * 退出
     */
    public function actionLogout ()
    {
        Yii::$app->user->logout();
        $this->redirect( [ 'login/login' ] );
    }
}
